<template>
  <div class='phoneInfo' v-if='showFlag'>
    <div style="position:relative">
      <!-- <div style="position:absolute;left:50%;bottom:50%;transform:translate(-50%);font-size:16px;color:#fff;">验证手机号</div>
      <img width='100%' src="~@/assets/images/myInfo/info_top.png" alt=""> -->
      <div class="phone">
        <div class="phoneTitle">
          手机号登录
        </div>
        <div class="SmallTitle">
          未注册的手机号验证后将自动创建账号
        </div>
        <div class="phoneInput">
          <span class="add" style="">+</span>
          <span class="bl" style="">86</span>
          <span class="gun" style=""></span>
          <input class="pooooo" style="" placeholder="请输入手机号" type="text" v-model="phoneNumber">
        </div>
        <div class="codeInput">
          <input class="inppp" style="" maxlength='6' placeholder="请输入验证码" type="text" v-model="checkCode">
          <span v-if='btnValue=="获取验证码"||btnValue=="重新获取"' :class="{ getdisable: getdisable }" 
          @click="getCode" id="v_code" class="ssspp" style="">{{btnValue}}</span>
          <span v-else class="eees" style="" :class="{ getdisable: getdisable }" 
          id="v_code">{{btnValue}}</span>
        </div>
        <div class="login">
          <img style="width:100%" src="~@/assets/images/myInfo/login123.png" alt="" @click="checkMessage">
        </div>
        <div class="isradio">
          <div class="radio" @click="isradio">
            <!-- <van-checkbox  v-model="checked" icon-size="14px"></van-checkbox> -->
            <img class="isis" v-if="!checked" src="../../assets/images/fradio.png" alt="">
            <img class="isis" v-if="checked" src="../../assets/images/gradio.png" alt="">
          </div>
          <div class="deal">
              同意并接受<span style="color:#009B63" @click='readEdBtnShow=true'>《中国人寿财险用户隐私保护策略》</span>
          </div>
        </div>
      </div>
    <Header v-if='readEdBtnShow' :clickLeft="clickLeft" titleValue='隐私保护政策'></Header>
    <Hgreement v-if='readEdBtnShow'></Hgreement>
      
    </div>
    <!-- <div class="midContent">
      <div style="margin-bottom:20px;text-align:left;">
        <img style="position:relative;top:5px;width:25px;height:25px;margin-right:10px" src="~@/assets/images/myInfo/info_phone.png" alt=""> <span style="font-size:17px;line-height:30px">请填写手机号及验证码</span>
      </div>
      <div style="margin-bottom:20px;color: #8A8982;font-size:15px;text-align:left;">我们将在系统中匹配您的保单信息以便查看</div>
      <div style="width:100%;text-align:left">
        <div style="margin:20px 0;height:26px;">
          <span style="color:red;width:10%">*</span>
          <span style="color: #8A8982;font-size:15px;width:20%;margin:0 20px 0 5px">手机号</span>
          <input style="width:60%;font-size:15px;" placeholder="请输入手机号" v-model="phoneNumber" type="text">
        </div>
        <div style="margin:25px 0;height:26px;">
          <span style="color:red;width:10%">*</span>
          <span style="color: #8A8982;font-size:15px;width:20%;margin:0 20px 0 5px">验证码</span>
          <input style="width:40%;font-size:15px;" maxlength='6' type="text" placeholder="请输入验证码" v-model="checkCode" >
          <div v-if='btnValue=="获取验证码"||btnValue=="重新获取"' style="text-align:center;color: #8A8982;padding: 3px 8px;float:right;font-size:13px;border: 1px solid #268F6E;border-radius: 13px;background:#fff" :class="{ getdisable: getdisable }" 
          @click="getCode" id="v_code">{{btnValue}}</div>
          <div v-else style="text-align:center;color: #8A8982;padding: 3px 8px;float:right;font-size:13px;border: 1px solid #268F6E;border-radius: 13px;background:#fff" :class="{ getdisable: getdisable }" 
          id="v_code">{{btnValue}}</div>
        </div>
      </div> -->
      <!-- <div class="btn" @click="checkMessage">下一步</div>
    </div> -->
  </div>
</template>
<script lang="ts">
import '../../style/reservaIndex_index.css';
import 'vant/lib/toast/style';
import 'vant/lib/dialog/style';
import 'vant/lib/checkbox/style';
import { Toast,Dialog ,Checkbox} from 'vant';
import { Component, Vue, Prop } from 'vue-property-decorator';
import { cloudApi,authorizeUrl,authorizeUrlAppid } from '@/api/indexApi';
import { Alert, log } from '@/utils';
import Header from '@/components/Header.vue';
import Hgreement from '@/components/agreement.vue';
import router from '@/router';
Vue.use(Dialog,Checkbox);
Component.registerHooks(['beforeRouteUpdate', 'beforeRouteLeave', 'beforeRouteLeave']);
@Component({
  components: { Header,Hgreement, [Checkbox.name]: Checkbox },
})
export default class MainPage extends Vue {
  phoneNumber = ''
  checkCode = ''
  checkInfoPhone = ''
  // address = 'https://wechattest.chinalife-p.com.cn/wechatpageview/Claimlistwx_index.html?appid=wxb1b70bf91a06f3e5&code=061m65Ga1OaPnA0w7AFa1uahTn0m65GD&state=ea70f6e5ccc29530148a5dcadb578670a988d18dd169e093bcc63c563b31d9caopenidoWcBG44J-8SeTxYHyH4NDyqPyTos'
  // app_id: string = this.address.split("?")[1].split("&")[0].split("=")[1];
  // code: string = this.address.split("&")[1].split("=")[1];
  openId: any = '';
  unionId:any='';
  route:any='';
  // unionId: string = 'ea70f6e5ccc29530148a5dcadb578670a988d18dd169e093bcc63c563b31d9ca';
  // uid:string = this.address.split("&")[2].split("=")[1];
  validateCodeType = ""
  checkInfo_type = "0"
  getdisable = false
  btnValue = '获取验证码'
  myCardList:any = []
  jumpflag = 0
  user_card_type= ''
  userId = ''
  user_phone = ''
  appid= ''
  code= ''
  source=''//页面来源
  sourceBack=''//返回几步
  showFlag:any=false;
  checked:boolean=false;
  readEdBtnShow:boolean=false;//是
  created() {  
  document.title = '注册'
      if(this.$route.query.route){//别的vue页面跳转来的
        this.showFlag=true
        this.route = this.$route.query.route
        this.openId = this.$route.query.openId
        this.unionId = this.$route.query.unionId
        if(!this.openId&&!this.unionId){//无openId  unionId 跳授权 
          let url=authorizeUrl+'dist/index.html'+authorizeUrlAppid+'state_checkPhoneInfo#wechat_redirect'
          sessionStorage.setItem('route',this.route)
          window.location.href=url  
        }
      }else{//授权回来的链接
        var address = location.href;
        console.log('zwh授权回来',address)
        this.appid = address.split("appid=")[1].split("&code")[0];
        this.code = address.split("code=")[1].split("&state")[0]
        this.source=address.split("checkPhoneInfo_openid")[1]
          console.log('zwh route',sessionStorage.getItem('route'))
        sessionStorage.setItem('sourceBack','xiaochengxu')//物理返回键回到小程序标识
        this.getShowInfo()
      }
  }
  mounted() {
      if (window.history && window.history.pushState) {
        // 向历史记录中插入了当前页
        history.pushState(null, null, document.URL);
        window.addEventListener('popstate', this.goBack, false);
     }    
   }
  destroyed () {
      window.removeEventListener('popstate', this.goBack, false);
  }
  goBack () {
    //指定返回路径
     if(sessionStorage.getItem('sourceBack')=='xiaochengxu'){
        sessionStorage.removeItem('sourceBack')
         if((window as any).wx.miniProgram){
          (window as any).wx.miniProgram.navigateBack({
            delta: history.length
          })
        }
      }
  }
  // getUnionIdAndOpenId(){
  //   var _this = this;
  //   cloudApi.getUnionIdAndOpenId({appid: _this.appid, code: _this.code}).then(function(res: any) {
  //       if (res.data) {
  //         if(res.data.openId){
  //           _this.unionId = res.data.unionId;
  //           _this.openId = res.data.openId;//公总号openId
  //           if(_this.source){//小程序来源 
  //             let wxOpenid =_this.source.split('_html')[0]//小程序openId
  //             let centerUrl=_this.source.split('_html')[1].split("#/checkPhoneInfo")[0]+'_index.html'  //跳转h5的html 
  //             let sourceUrl=authorizeUrl+centerUrl+authorizeUrlAppid+_this.unionId+'openid'+wxOpenid+'#wechat_redirect'
  //             sessionStorage.setItem('route', '')
  //             sessionStorage.setItem('sourceUrl', sourceUrl)
  //             console.log('小程序来源sourceUrl',sourceUrl)
  //           }
  //           if(sessionStorage.getItem('route')){//vue页面来源
  //             _this.route = sessionStorage.getItem('route')
  //             sessionStorage.setItem('sourceUrl', '')
  //            console.log('vue来源route',_this.route)
  //           }
  //         }else{
  //            Dialog.alert({ title: '温馨提示', message: "未获取到openId" })
  //         }
  //       }else{
  //          Dialog.alert({ title: '温馨提示', message: "网络请求不给力，请稍后重试" })
  //       }
  //     });
  // }
  getShowInfo(){
    var _this = this;
    cloudApi.showInfo({app_id: _this.appid, code: _this.code}).then(function(res: any) {
        if (res.data) {
          if(res.data.openId){
            _this.openId = res.data.openId;//公总号openId
            _this.myInformation_getbind()
          }else{
            //  Dialog.alert({ title: '温馨提示', message: "未获取到openId" })
              Toast('网络请求不给力，请稍后重试');
          }
        }else{
           Toast('网络请求不给力，请稍后重试');
          //  Dialog.alert({ title: '温馨提示', message: "网络请求不给力，请稍后重试" })
        }
      });
  }
myInformation_getbind(){
    const data = {
        openid: this.openId,
        unionid: ""
    }
    let _this= this
    cloudApi.getMyBussinessCardURL(data).then(res => {
      if(res.status = 200){
        let dataLength = res.data.result
        let wxOpenid =_this.source.split('_userId')[0]//小程序openId
        let uid = _this.source.split('_userId')[1].split("_html")[0]//userId
        let centerUrl=_this.source.split('_html')[1].split("#/checkPhoneInfo")[0]+'_index.html'  //跳转h5的html     
          if(_this.source){//小程序来源 
             cloudApi.getThreeidById({id:uid}).then(resDate => {
                _this.unionId = resDate.data.unionid
                let sourceUrl=authorizeUrl+centerUrl+authorizeUrlAppid+_this.unionId+'openid'+wxOpenid+'#wechat_redirect'
                sessionStorage.setItem('route', '')
                sessionStorage.setItem('sourceUrl', sourceUrl)
                console.log('小程序来源sourceUrl',sourceUrl)
                if(dataLength.length!== 0){//小程序查询数据为空 在此查询有值 返回小程序
                  let htmlUrl:any =sessionStorage.getItem('sourceUrl')
                  wx.miniProgram.redirectTo({ 
                      url: '/pages/webview/webview?url='+encodeURIComponent(htmlUrl)+'&flag=1'
                  });
                }else{//查询数据为空注册/登录
                 _this.showFlag=true
                }
              }) 
            }
            if(sessionStorage.getItem('route')){//vue页面来源
              _this.route = sessionStorage.getItem('route')
              sessionStorage.setItem('sourceUrl', '')
             console.log('vue来源route',_this.route)
            }
         
      }
    })
  }
  //获取验证码
  getCode(){
    // 手机号为空
    if (this.phoneNumber === '') {
      Toast('请输入手机号');
      return;
    } else if (!/^1[3456789]\d{9}$/.test(this.phoneNumber)) {
      // 检测手机号格式
      Toast('请输入正确的手机号');
      return;
    }
    cloudApi.getValidateCode({phoneNumber:  window.btoa(this.phoneNumber)}).then(res => {
      if(res.status == 200){
        if (res.data.requestTime == "1") {
          Dialog.alert({ title: '温馨提示', message: "尊敬的客户，您获取验证码的频率过高，请稍后获取！" })
          return;
        }
        this.checkInfo_type = "0"; //电商可以验证码
        if (res.data.getValidateCode1.respCode == "01") {
          Dialog.alert({ title: '温馨提示', message: "手机验证码已经发出！" })
            this.validateCodeType = "01"; //注册调用成功
            this.verifiction_code2(); //客户验证
        } else if (res.data.getValidateCode1.respCode == "10") {
            //电商获取不到验证码
            this.checkInfo_type = "1"; //电商获取不到验证码
            this.information_checkInfo();
        } else {
            if (res.data.getValidateCode2.respCode == "01") {
              Dialog.alert({ title: '温馨提示', message: "手机验证码已经发出！" })
                this.validateCodeType = "02"; //登录调用成功
                this.verifiction_code2(); //客户验证
            } else {
                if (res.data.getValidateCode1.respCode == "10" || res.data.getValidateCode1.respCode == "49" ||
                    res.data.getValidateCode2.respCode == "10" || res.data.getValidateCode2.respCode == "49") {
                    //电商获取不到验证码
                    this.checkInfo_type = "1"; //电商获取不到验证码
                    this.information_checkInfo();
                } else {
                  Dialog.alert({ title: '温馨提示', message: "发送验证码失败，请稍后再次获取！" })
                }
            }
          }
       }
    })
  }
  //倒计时
  verifiction_code2(){
    var count = 60;
    const _this = this
    _this.getdisable = false;
    var time = setInterval(function () {
        _this.getdisable = true;
        count--;
        _this.btnValue = count + "秒后获取";
        if (count == -1) {
            clearInterval(time);
            _this.btnValue = "重新获取";
            _this.getdisable = false;
        }
    }, 1000)
  }
  information_checkInfo(){
    //  Toast.loading({
    //   duration: 0,
    //   message: '加载中...',
    //   forbidClick: true,
    // });
    const data = {
      open_id: this.openId,
      mobile_Phone: window.btoa(this.phoneNumber) //手机号
    }
    cloudApi.getCheckCodeOneURL(data).then(res=> {
      // Toast.clear();
      if(res.status == 200){
        if (res.data.result == "1") {
          Dialog.alert({ title: '温馨提示', message: "手机验证码已经发出！" })
          this.checkInfoPhone = this.phoneNumber;
          this.validateCodeType = "02"; //登录调用成功
          this.verifiction_code2(); //客户验证
        } else if (res.data.result == "2") {
          Dialog.alert({ title: '温馨提示', message: "尊敬的用户，您获取验证码的频率过高，请稍后再次获取!" })
        } else {
          Dialog.alert({ title: '温馨提示', message: "发送手机验证码失败，请重新获取！" })
        }
      }else{
        Dialog.alert({ title: '温馨提示', message: "暂时不能为您服务，请拨打95519或4008695519" })
      }
    })
  }
  checkMessage(){//点击下一步按钮
    if (this.btnValue=='获取验证码') {
      Toast('请先获取验证码');
      return;
    }
    if (!this.checked) {
      Toast('请先同意并接受协议')
      return
    }
    if(this.checkInfo_type!== "0"){//电商验证
      const data = {
        open_id: this.openId,
        verifyCode: this.checkCode //验证码
      }
      cloudApi.checkMessageAuthen(data).then(res =>{
        if(res.status == 200){
          if(res.data.result == "1"){
            this.getUserInfo()
          } else if (res.data.result == "2") {
            Dialog.alert({ title: '温馨提示', message: "短信验证码已失效，请重新获取！" })
            return;
          } else {
            Dialog.alert({ title: '温馨提示', message: "短信验证码不正确，请重新填写！" })
            return;
          }
        }
      })
    }else {
      const data1 = {
        phoneNumber: btoa(this.phoneNumber),
        validateCode: this.checkCode,
        validateCodeType: this.validateCodeType
      }
      cloudApi.checkValidateCode(data1).then(res => {
        var data = JSON.parse(decodeURIComponent(atob(res.data.result)));
        console.log(data)
          if(data.checkValidateCode1.respCode == "01"){
            this.getUserInfo()
          }else{
            Dialog.alert({ title: '温馨提示', message: data.checkValidateCode1.errorMsg })
          }
      })
    }
  }
  //通过手机号查询是否绑定是三要素
  getUserInfo(){
    const data = {
      phone: this.phoneNumber,
      openid: this.openId,
      unionid:this.unionId,
      datasource: 'zgs'
    }
    cloudApi.userByPhone(data).then(res => {
      var data1 = res.data.result;
      if (data1 == '' || data1 == "" || data1 == undefined || data1 == "''") {
          this.jumpflag = 0;
          //获取userid
          this.information_bindding();
      } else {
          this.myCardList = [];
          this.myCardList.push(data1)
          this.myCardList[0]["relation1"] = "本人"; //与本人关系
          this.jumpflag = 1;
          console.log("myCardList",this.myCardList)
          this.information_bindding()
      }
    })
  }
  //保存接口
  information_bindding(){
    const data = {
      openid: this.openId,
      user_phone: this.phoneNumber,
      verifyCode: this.checkCode,
      type: this.validateCodeType,
      unionid:this.unionId
    } 
    let _this =this  
    cloudApi.queryUserInfoByPhone(data).then(res => {
      var data = JSON.parse(decodeURIComponent(atob(res.data.result)));
        //alert("获取三要素信息" + JSON.stringify(data));
        if (data.result == "error") {
          Dialog.alert({ title: '温馨提示', message: data.inf })
        } else {
            _this.user_card_type = data.result.user_card_type; //证件类型
            _this.userId = data.result.user_id; //获取到userid，id中存放userID的值      
            _this.user_phone = data.result.user_phone; //手机号
            let userData:any={
              "openId":_this.openId,
              "mobile":_this.user_phone,
              "userId":_this.userId,
              "unionId":_this.unionId
            }
            sessionStorage.setItem("userData",JSON.stringify(userData))   
            if (_this.jumpflag == 0) {
                if(_this.route){//vue页面进来带的返回链接传给下个页面
                  _this.$router.push({path: 'idCardInfo',query: {route:_this.route}});
                }else{
                  _this.$router.push('idCardInfo');
                } 
            } else if (_this.jumpflag == 1) {
               if(_this.route){//别的页面进来需要返回原来页面
                  let route:any = JSON.parse(_this.route)
                  _this.$router.push(route)
                }else if(sessionStorage.getItem('sourceUrl')){//小程序来源
                   let htmlUrl:any =sessionStorage.getItem('sourceUrl')
                    wx.miniProgram.redirectTo({ 
                        url: '/pages/webview/webview?url='+encodeURIComponent(htmlUrl)+'&flag=1'
                    });
                }else{
                _this.$router.push("personalCard")
              } 
            }
        }
    })
  }
  clickLeft(){
    this.readEdBtnShow=false
  }
  isradio(){
    this.checked = !this.checked
  }
}
</script>
<style lang="less" scoped>
.eees{
text-align:center;
color: #8A8982;
padding: 3px 8px;
// float:right;
word-spacing: normal;
font-size:13px;
}
.ssspp{
  font-size: 14px;
  // font-family: PingFang SC, PingFang SC-Regular;
  font-weight: 400;
  color: #009b63;
  line-height: 1;
}
.inppp{
  width: 50%;
font-size:16px;
}
.pooooo{
  flex:1;
  font-size:16px;
}
.gun{
  margin-left: 10px;
  margin-right: 10px;
  width: 1px;
  height: 12px;
  background-color: #C8C7C7;
}
.bl{
  
  font-size: 18px;
  line-height: 1;
  // font-family: DIN Alternate, DIN Alternate-Bold;
  font-weight: 700;
  color: #222222;
}
.add{
  
  margin-left: 1px;
  font-size: 19px;
  color: #222222;
  // font-family: PingFang SC, PingFang SC-Regular;
  font-weight: 400;
}
.isis{
  width: 14px;
  height: 14px;
}
.phoneInfo{
  // background: url("../../assets/images/myInfo/info_center.png") no-repeat;
  background-color: #fff;
  background-size:100% 100%;
  position:absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  text-align: center;
}
.midContent{
  width: 90%;
  background: #FFFFFF;
  box-shadow: 0px 15px 15px 0px rgba(4, 0, 0, 0.05);
  border-radius: 40px;
  position: relative;
  left: 50%;
  transform: translateX(-50%);
  padding: 20px;
}
.btn{
  width: 100%;
  height: 36px;
  line-height: 36px;
  background: #00A08A;
  border-radius: 18px;
  color:#fff;
  font-size: 17px;
}
.phone{
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding-top: 48px;
  padding-left: 38px;
  padding-right: 38px;
  position: relative;
  .phoneTitle{
    font-size: 24px;
    line-height: 1;
    color: #222222;
    text-align: left;
    // font-family: PingFang SC, PingFang SC-Semibold;
    font-weight: 600;
  }
  .SmallTitle{
    margin-top: 11px;
    font-size: 14px;
    color: #666666;
    text-align: left;
    line-height: 1;
    // font-family: PingFang SC, PingFang SC-Regular;
    font-weight: 400;  
    margin-bottom: 40px;
  }
  .phoneInput{
    height: 60px;
    text-align: left;
    display: flex;
    align-items: center;
    border: 1px;
    border-bottom-style: solid;
    border-bottom-color: #c8c7c7;
  }
  .codeInput{
    height: 60px;
    text-align: left;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border: 1px;
    border-bottom-style: solid;
    border-bottom-color: #c8c7c7;
  }
  .login{
    width: 100%;
    margin-top: 50px;
    margin-bottom: 50px;
  }
  /deep/  .van-checkbox__icon--round .van-icon {
    width: 14px;
    height: 14px;
  }
  .isradio{
    text-align: left;
    font-size: 12px;
    color: #999999;
    display: flex;
    justify-content: space-between;
    // font-family: PingFang SC, PingFang SC-Regular;
    font-weight: 400;
    line-height: 1;
    .radio{
      height: 32px;
      display: inline-table;
      padding-top: 3px;
      margin-right: 5px;
    }
    .deal{
      font-size: 12px;
      line-height: 18px;
      // font-family: PingFang SC, PingFang SC-Regular;
      font-weight: 400;
      display: inline;
      flex: 1;
    }
    
  }
    
}
</style>

